package lib

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"time"
	//	"io/ioutil"
	"net/http"
	//	"time"

	"github.com/gorilla/mux"
)

type HTTPService struct {
	config *Config
}

func NewHTTP(conf *Config) *HTTPService {
	return &HTTPService{
		config: conf,
	}
}

func (s *HTTPService) Start() {
	r := mux.NewRouter()
	r.HandleFunc("/", s.RedirectSample)
	r.HandleFunc("/xlsx2csv", s.XLSX2CSV)
	r.PathPrefix("/sample/").Handler(http.StripPrefix("/sample/",
		http.FileServer(http.Dir(fmt.Sprintf("%s/sample", s.config.WebRoot)))))
	r.NotFoundHandler = http.HandlerFunc(s.NotFoundHandle)

	InfoLogger.Println("http service starting")
	InfoLogger.Printf("Please open http://%s\n", s.config.Listen)
	http.ListenAndServe(s.config.Listen, r)
}

func (s *HTTPService) NotFoundHandle(writer http.ResponseWriter, request *http.Request) {
	http.Error(writer, "handle not found!", 404)
}

func (s *HTTPService) RedirectSample(writer http.ResponseWriter, request *http.Request) {
	http.Redirect(writer, request, "/sample/index.html", 301)
}

func (s *HTTPService) XLSX2CSV(writer http.ResponseWriter, request *http.Request) {

	delimiter := request.FormValue("delimiter")
	sheetIndex, er := strconv.Atoi(request.FormValue("sheetIndex"))
	if er != nil {
		sheetIndex = 0
	}

	if len(delimiter) == 0 {
		delimiter = ","
	}

	request.ParseMultipartForm(32 << 20)
	file, FileHeader, err := request.FormFile("upload")
	if err != nil {
		ErrLogger.Println(err)
		http.Error(writer, err.Error(), 500)
		return
	}
	defer file.Close()

	dest_dir := filepath.Join(s.config.TempPath, time.Now().Format("20060102150405"))
	if _, err := os.Stat(dest_dir); os.IsNotExist(err) {
		os.MkdirAll(dest_dir, 0777)
	}
	dest_file := filepath.Join(dest_dir, FileHeader.Filename)
	dest, err := os.Create(dest_file)
	if err != nil {
		ErrLogger.Println(err)
		http.Error(writer, err.Error(), 500)
		return
	}
	defer dest.Close()

	_, err = io.Copy(dest, file)
	if err != nil {
		ErrLogger.Println(err)
		http.Error(writer, err.Error(), 500)
		return
	}

	err, buf := generateCSVFromXLSXFile(dest_file, delimiter, sheetIndex)
	if err != nil {
		ErrLogger.Println(err)
		http.Error(writer, err.Error(), 500)
		return
	}

	defer time.AfterFunc(time.Second*10, func() {
		err := os.RemoveAll(dest_dir)
		if err != nil {
			ErrLogger.Println(err)
		}
	})

	writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%d.csv", time.Now().UnixNano()))
	writer.Header().Set("Content-Type", "application/vnd.ms-excel")
	writer.Write(buf.Bytes())
}
